package tableapi;

import bean.SensorReading;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
import org.apache.flink.types.Row;

public class TableTest1_Example {

    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        DataStreamSource<String> inputStream = env.readTextFile("D:\\CS\\MyDemo\\gmall-flink\\flink-demo\\src\\main\\resources\\sensor.txt");

        SingleOutputStreamOperator<SensorReading> dataStream = inputStream.map(line -> {
            String[] fields = line.split(",");
            return new SensorReading(fields[0], new Long(fields[1]), new Double(fields[2]));
        });

        // table api 环境
        StreamTableEnvironment tableEnv = StreamTableEnvironment.create(env);

        // 基于流创建一张表
        Table dataTable = tableEnv.fromDataStream(dataStream);

        // table api
        Table resultTable = dataTable.select("id, temperature").where("id='sensor_1'");

        // sql
        tableEnv.createTemporaryView("sensor",dataTable);
        String sql = "select id,temperature from sensor where id ='sensor_1'";
        Table resultSqlTable = tableEnv.sqlQuery(sql);

        // 输出 (toAppendStream追加模式、toRetractStream更新模式)
//        tableEnv.toAppendStream(resultTable, Row.class).print("result");
        tableEnv.toAppendStream(resultSqlTable, Row.class).print("sql");
        // new输出 （toDataStream仅追加/仅插入、toChangelogStream更新）
        DataStream<Row> resultStream = tableEnv.toDataStream(resultSqlTable);

        resultStream.print("new");
        env.execute();

    }
}
